package com.blockmeta.bbs.overallserviceapplication.activity.login;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.SecurityUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.AppCode;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.R2;
import com.blockmeta.bbs.overallserviceapplication.net.api.NetApi;
import com.blockmeta.bbs.businesslibrary.pojo.LoginPOJO;
import com.blockmeta.bbs.overallserviceapplication.umeng.ThirdLoginDataPOJO;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 绑定账号页面
 */
public class BindAccountActivity extends BaseActivity {
    @BindView(R2.id.iv_head_portrait)
    ImageView mIvHeadPortrait;
    @BindView(R2.id.edit_phone_number)
    EditText mEditPhoneNumber;
    @BindView(R2.id.edit_verification_code)
    EditText mEditVerificationCode;
    private Context mContext;

    private String openId = ThirdLoginDataPOJO.getINSTANCE().getUid();
    private String unionId = ThirdLoginDataPOJO.getINSTANCE().getUnionid();
    private String name = ThirdLoginDataPOJO.getINSTANCE().getName();
    private String avatar = ThirdLoginDataPOJO.getINSTANCE().getIconUrl();
    private String type = ThirdLoginDataPOJO.getINSTANCE().getType();
    private String stoken = ThirdLoginDataPOJO.getINSTANCE().getStoken();

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        mContext = BindAccountActivity.this;
        setTitleText("");
        return LayoutInflater.from(mContext).inflate(R.layout.activity_bind_account, null);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //设置头像
        Glide.with(this).load(avatar).into(mIvHeadPortrait);
    }

    @OnClick({R2.id.btn_bind, R2.id.tv_bind_switch, R2.id.btn_postpone})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_bind) {
            String account = mEditPhoneNumber.getText().toString();
            String pwd = mEditVerificationCode.getText().toString();
            BindOrPostpone(openId, unionId, name, avatar, type, 0, account, pwd,stoken);

        } else if (i == R.id.tv_bind_switch) {
            startActivity(new Intent(this, BindPhoneActivity.class));
            finish();

        } else if (i == R.id.btn_postpone) {
            BindOrPostpone(openId, unionId, name, avatar, type, 1, null, null,stoken);
        }
    }

    /**
     * 绑定账号或者推迟绑定
     *
     * @param openId   三方登陆的唯一标识
     * @param nickName 昵称
     * @param avatar   头像链接
     * @param type     使用哪个三方平台登陆的 weixin qq weibo
     * @param register 推迟绑定时register=1 其它=0
     * @param account  账号
     * @param passWord 密码
     */
    private void BindOrPostpone(String openId, String unionId, String nickName, String avatar, String type, int register, String account, String passWord,String stoken) {
        HashMap<String, String> checkMap = new HashMap<>();
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);

        checkMap.put("openid", openId);
        checkMap.put("unionid", unionId);
        checkMap.put("nickname", nickName);
        checkMap.put("avatar", avatar);
        checkMap.put("type", type);
        checkMap.put("stoken",stoken);
        checkMap.put("register", register + "");
        checkMap.put("username", account);
        checkMap.put("password", SecurityUtil.MD5(passWord));
        checkMap.put("device_id", DeviceUtil.getIMEI());
        checkMap.put("product_code", myAppCode);
        checkMap.put("source","app");
        checkMap.put("bind_type","2");

        RetrofitFactory.getRootRetrofit().create(NetApi.SocialBind.class)
                .bindSocial(RequestBody.create(NetApi.sMediaType,new Gson().toJson(checkMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<LoginPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<LoginPOJO>(mContext) {
                    @Override
                    public void onNext(LoginPOJO loginPOJO) {
                        saveUserInfo(loginPOJO);
                        finish();
                    }
                });
    }


    /**
     * 保存用户信息，进行持久化
     */
    private void saveUserInfo(LoginPOJO loginPOJO) {
        if (loginPOJO.userInfo==null){return;}
        UserPhonePOJO userPhonePOJO = new UserPhonePOJO();
        userPhonePOJO.setEmail(loginPOJO.userInfo.email);
        userPhonePOJO.setMobile(loginPOJO.userInfo.mobile);
        userPhonePOJO.setUid(Integer.valueOf(loginPOJO.userInfo.uid));
        userPhonePOJO.setUserName(loginPOJO.userInfo.userName);
        userPhonePOJO.setToken(loginPOJO.token);

        AccountHelper.doLogin(userPhonePOJO);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }
}
